﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameDataHelper;
using Microsoft.Win32;
using System.Drawing;
using Image = System.Windows.Controls.Image;
using Point = System.Drawing.Point;

namespace BoxEditor
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
     List<Level> levels=new List<Level>();
        private Level currentLevel=null;
        private int SetType = -1;
        private int defaultWidth = 30,defaultHeight=30;
        public MainWindow()
        {
            InitializeComponent();
            cb_levels.ItemsSource = levels;
            cb_levels.DisplayMemberPath = "name";
            cb_levels.SelectedValuePath = "ID";
            this.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(MainWindow_MouseLeftButtonDown);
        var fileds=new List<filed>()   {
                                           new filed()
                                               {
                                                   id = 1,
                                                   name = "河流"
                                               },
                                               new filed()
                                                   {
                                                       id=2,
                                                       name="草地"
                                                   },
                                                      new filed()
                                                   {
                                                       id=3,
                                                       name="障碍"
                                                   }
                         
                                       };
           cb_filed.ItemsSource = fileds;
            cb_filed.DisplayMemberPath = "name";
            cb_filed.SelectedValuePath = "id";
            cb_filed.SelectedIndex = 0;
            var fileds1=new List<filed>()
                                       {
                                           new filed()
                                               {
                                                   id = 1,
                                                   name = "箱子"
                                               },
                                               new filed()
                                                   {
                                                       id=2,
                                                       name="目标"
                                                   },
                                                      new filed()
                                                   {
                                                       id=3,
                                                       name="终点"
                                                   },
                                                                new filed()
                                                   {
                                                       id=4,
                                                       name="主角"
                                                   }
                         
                                       };
            cb_items.ItemsSource = fileds1;
            cb_items.DisplayMemberPath = "name";
            cb_items.SelectedValuePath = "id";
            cb_items.SelectedIndex = 0;
        }

        void MainWindow_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            System.Windows.Point mposition = e.GetPosition(this);
            switch (SetType )
            {
                case -1:
                    break;
                case  0:
                    break;
            }
            if (mposition.X < 700)
            {
                label1.Content = mposition.X + "," + mposition.Y;
                //         throw new NotImplementedException();
                if (radioButton1.IsChecked.Value)
                {
                    currentLevel.DefaultPosition = mposition;
                }
                else if (radioButton2.IsChecked.Value)      //编辑地形
                {

                    setField(mposition);

                }
                else   if (radioButton3.IsChecked.Value)        //添加游戏元素
                {
                    AddElement(mposition);
                }
                Refresh();
            
            }
        }

        public void AddNewLevel(Dictionary<string ,string> myString )
        {
            currentLevel = new Level(int.Parse(myString["id"]), myString["name"]);
            int row = int.Parse(myString["rowCount"]),column=int.Parse(myString["ColumnCount"]);
            currentLevel.ColuCount = column;
            currentLevel.RowCount = row;
            currentLevel.MapArray=new int[row,column];
            for (int i = 0; i < currentLevel.MapArray.GetLength(0); i++)
            {
                for (int j = 0; j < currentLevel.MapArray.GetLength(1); j++)
                {
                    currentLevel.MapArray[i, j] = 1;
                }
            }
            levels.Add(currentLevel);
           cb_levels.SelectedIndex = cb_levels.Items.Count-1;
            Refresh();
        }

        private void cb_levels_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Refresh();//更新界面UI
        }
        private void InitializePicture(Level myLevel)
        {
            canvas1.Children.Clear();
            BitmapImage[] images = new BitmapImage[7];
            images[0] = new BitmapImage(new Uri(@"/Images/target.png", UriKind.Relative));       //目标);
            images[1] = new BitmapImage(new Uri(@"/Images/box.png", UriKind.Relative));       //箱子);
            images[2] = new BitmapImage(new Uri(@"/Images/endpicture.png", UriKind.Relative));       //终点);
            images[3] = new BitmapImage(new Uri(@"/Images/grass.png", UriKind.Relative));       //草地);
            images[4] = new BitmapImage(new Uri(@"/Images/river.png", UriKind.Relative));       //河流);
            images[5] = new BitmapImage(new Uri(@"/Images/sheep.png", UriKind.Relative));       //羊 );
            images[6] = new BitmapImage(new Uri(@"/Images/stone.png", UriKind.Relative));       //石头);
            int defaultWidth = 30;
            int defaultHeight = 30;
            System.Windows.Point defaultPosition = myLevel.DefaultPosition;
            int[,] mapArray = myLevel.MapArray;
            for (int i = 0; i < mapArray.GetLength(1); i++)
            {
                for (int j = 0; j < mapArray.GetLength(0); j++)
                {
                    switch (mapArray[j, i])
                    {
                        case 0:
                            break;
                        case 1:
                            Image grass = new Image();
                            grass.Source = images[3];
                            grass.Width = defaultWidth;
                            grass.Height = defaultHeight;
                            grass.RenderTransform = new TranslateTransform()
                            {
                                X = defaultPosition.X + i * defaultWidth,
                                Y = defaultPosition.Y + j * defaultHeight
                            };
                            canvas1.Children.Add(grass);
                            Canvas.SetZIndex(grass, 2);
                            break;
                        case 2:
                            Image stone = new Image();
                            stone.Source = images[6];
                            stone.Width = defaultWidth;
                            stone.Height = defaultHeight;
                            stone.RenderTransform = new TranslateTransform()
                            {
                                X = defaultPosition.X + i * defaultWidth,
                                Y = defaultPosition.Y + j * defaultHeight
                            };
                            canvas1.Children.Add(stone);
                            Canvas.SetZIndex(stone, 2);
                            //  test = stone;
                            break;
                        case 3:
                            Image river = new Image();
                            river.Source = images[4];
                            river.Width = defaultWidth;
                            river.Height = defaultHeight;
                            river.RenderTransform = new TranslateTransform()
                            {
                                X = defaultPosition.X + i * defaultWidth,
                                Y = defaultPosition.Y + j * defaultHeight
                            };
                            canvas1.Children.Add(river);
                            Canvas.SetZIndex(river, 2);
                            break;
                        default:
                            break;
                    }
                }
            }
            //箱子
            for (int i = 0; i < myLevel.Boxes.Count; i++)
            {
                Image image = new Image();

                image.Source = images[1];
                image.Width = defaultWidth;
                image.Height = defaultHeight;
                image.RenderTransform = new TranslateTransform()
                {
                    X = myLevel.Boxes[i].X * defaultWidth + defaultPosition.X,
                    Y = myLevel.Boxes[i].Y * defaultHeight + defaultPosition.Y
                };
                canvas1.Children.Add(image);
                Canvas.SetZIndex(image, 3);
            }
            //目标
            foreach ( Point point in myLevel.Targets)
            {
                Image targetImage = new Image();
                targetImage.Source = images[0];
                targetImage.Width = defaultWidth;
                targetImage.Height = defaultHeight;
                targetImage.RenderTransform = new TranslateTransform()
                {
                    X = point.X * defaultWidth + defaultPosition.X,
                    Y = point.Y * defaultHeight + defaultPosition.Y
                };
                canvas1.Children.Add(targetImage);
                Canvas.SetZIndex(targetImage, 3);
            }

            //人物
            Image mainRole = new Image();
            //   rolePosition.X = defaultPosition.X*defaultWidth + startPosition.X*defaultWidth;
            //     rolePosition.Y = defaultPosition.Y*defaultHeight + startPosition.Y*defaultHeight;
            mainRole.Source = images[5];
            mainRole.Width = defaultWidth;
            mainRole.Height = defaultHeight;
            mainRole.RenderTransform = new TranslateTransform()
            {
                X = myLevel.StartPosition.X * defaultWidth + defaultPosition.X,
                Y = myLevel.StartPosition.Y * defaultHeight + defaultPosition.Y
            };
            canvas1.Children.Add(mainRole);
            Canvas.SetZIndex(mainRole, 5);
            //终点
            Image endImage = new Image();
            endImage.Source = images[2];
            endImage.RenderTransform=new TranslateTransform()
                                         {
                                             X = myLevel.ExitPosition.X*defaultWidth+ defaultPosition.X,
                                             Y = myLevel.ExitPosition.Y*defaultHeight + defaultPosition.Y
                                         };
            endImage.Width = defaultWidth;
            endImage.Height = defaultHeight;
            canvas1.Children.Add(endImage);
            Canvas.SetZIndex(endImage, 5);
        }
        private void Refresh()
        {
          //  cb_levels.ItemsSource = levels;
          
            if (cb_levels.SelectedIndex >= 0)
            {  
                currentLevel = levels[cb_levels.SelectedIndex];
                lb_levelInfor.Content = "当前选择的关卡为\n" + currentLevel.name + "\nID为:\n" +
                                       currentLevel.ID;
          
            }
            else
            {
                lb_levelInfor.Content = "无相关信息";
            }
            if (currentLevel != null)
            {
                lb_levelInfor.Content = "当前选择的关卡ID为;\n" + currentLevel.ID + "\n名称：\n" + currentLevel.name;
                InitializePicture(currentLevel);
            }
            else
            {
                lb_levelInfor.Content = "无相关信息";
            }
            lb_levels.Content = "关卡总数为:\n" + levels.Count;
        }

        private void openMap_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "选择保存过的地图信息文件";//对话框标题
            ofd.Filter = "数据存储文件(*.xml)|*.xml";
            if (ofd.ShowDialog() == true)
            {
                levels.Clear();
                levels = DataControl.GetLevelsFromXML(ofd.FileName);
                cb_levels.ItemsSource = levels;

                cb_levels.DisplayMemberPath = "name";
                cb_levels.SelectedValuePath = "ID";
                cb_levels.SelectedIndex = 0;
            }
            Refresh();
            //  mapShow.Parent = this;
        }

        private void bt_save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                DefaultExt = "xml",
                Filter = "数据存储文件(*.xml)|*.xml"
            };
            try
            {
                if ((bool)saveFileDialog.ShowDialog())
                {
                    using (Stream stream = saveFileDialog.OpenFile())
                    {
                        StringBuilder text = DataControl.GetStringFromLevels(levels);
                        byte[] value = Encoding.UTF8.GetBytes(text.ToString());
                        stream.Write(value, 0, value.Length);
                        stream.Close();
                    }
                }
            }
            catch
            {
                MessageBox.Show("文件保存失败？！");
            }
        }
        private void bt_AddLevel_Click(object sender, RoutedEventArgs e)
        {
            SetType = -1;
            NewLevel newLevel = new NewLevel(this);
            newLevel.Show();
        }
        private void bt_new_Click(object sender, RoutedEventArgs e)
        {
            SetType = -1;
            if (levels.Count > 0)
            {
                if (MessageBox.Show(this, "确定清除原有关卡信息?") == MessageBoxResult.Yes)
                {
                    levels.Clear();
                }
            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            switch (int.Parse(cb_items.SelectedValue.ToString()))
            {
                case 1:     //箱子
                    currentLevel.Boxes.Clear();
                    break;

                  case 2:   //目标    
                    currentLevel.Targets.Clear();
                    break;

                      case 3:       //终点
                //    currentLevel.ExitPosition = new Point(1,1);
                    break;
                 
                      case 4:       //主角
                //          currentLevel.StartPosition = new Point(5, 5);
                    break;

            }
            Refresh();
        }
        public void setField(System.Windows.Point Position)
        {
            int px = (int)currentLevel.DefaultPosition.X + currentLevel.ColuCount * defaultWidth;
            int py = (int)currentLevel.DefaultPosition.Y + currentLevel.RowCount * defaultHeight;
           
            //判断点击位置和地图信息之间关系
            if (Position.X < currentLevel.DefaultPosition.X || Position.Y < currentLevel.DefaultPosition.Y || Position.X > px || Position.Y > py)
            {
                return;
            }
            int x1 = ((int) Position.X - (int) currentLevel.DefaultPosition.X)/defaultWidth;
            int y1 = ((int)Position.Y - (int)currentLevel.DefaultPosition.Y) / defaultHeight;
            switch (int.Parse(cb_filed.SelectedValue.ToString()))
            {
                case 1:     //河流
                    currentLevel.MapArray[y1, x1] = 3;
                    break;
                case 2:   //草地    
                    currentLevel.MapArray[y1, x1] = 1;
                    break;
                case 3:       //障碍
                    currentLevel.MapArray[y1, x1] =2;
                    break;

            }
        }
        public void AddElement(System.Windows.Point Position)
        {
            int px = (int)currentLevel.DefaultPosition.X + currentLevel.ColuCount*defaultWidth;
            int py = (int)currentLevel.DefaultPosition.Y + currentLevel.RowCount * defaultHeight;
           
            //判断点击位置和地图信息之间关系
            if (Position.X < currentLevel.DefaultPosition.X || Position.Y < currentLevel.DefaultPosition.Y||Position.X>px||Position.Y>py)
            {
                return;
            }
            int x1 = ((int)Position.X - (int)currentLevel.DefaultPosition.X) / defaultWidth;
            int y1 = ((int)Position.Y - (int)currentLevel.DefaultPosition.Y) / defaultHeight;
            switch (int.Parse(cb_items.SelectedValue.ToString()))
            {
                case 1:     //箱子
                    currentLevel.Boxes.Add(new Point(x1,y1));

                    break;
                case 2:   //目标    
                    //   currentLevel.Targets.Clear();
                    currentLevel.Targets.Add(new Point(x1, y1));
                    break;
                case 3:       //终点
                    // currentLevel.ExitPosition = new Point(1, 1);
                    currentLevel.ExitPosition = new Point(x1, y1);

                    break;
                case 4:       //主角
                    //          currentLevel.StartPosition = new Point(5, 5);
                    currentLevel.StartPosition = new Point(x1, y1);
                    break;
            }
        }

        private void bt_deleteLevel_Click(object sender, RoutedEventArgs e)
        {
            if (cb_levels.SelectedIndex!=-1)
            {
                 levels.RemoveAt(cb_levels.SelectedIndex);
            }
           
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            if (textBox1.Text!="")
            {
                try
                {
                    currentLevel.ID = int.Parse(textBox1.Text);
                    Refresh();
                }
                catch (Exception)
                {
                    
                 
                }
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if (textBox2.Text != "")
            {
                try
                {
                    currentLevel.name = textBox2.Text;
                    Refresh();
                }
                catch (Exception)
                {


                }
            }
        }
    }
    public class filed
    {
        public int id { get; set; }
        public string name { get; set; }
        public filed()
        {
            int i = 0;
        }
    }
    
}
